
/*
 * @(#)MaintFormSectionAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.web;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.form.bean.FormElement;
import com.dcivision.form.bean.FormElementType;
import com.dcivision.form.bean.FormGroup;
import com.dcivision.form.bean.FormPage;
import com.dcivision.form.bean.FormRecord;
import com.dcivision.form.bean.FormSection;
import com.dcivision.form.bean.MtmFormPageFormSection;
import com.dcivision.form.bean.MtmFormSectionFormElement;
import com.dcivision.form.core.FormSubmissionManager;
import com.dcivision.form.dao.FormElementDAObject;
import com.dcivision.form.dao.FormGroupDAObject;
import com.dcivision.form.dao.FormPageDAObject;
import com.dcivision.form.dao.FormRecordDAObject;
import com.dcivision.form.dao.FormSectionDAObject;
import com.dcivision.form.dao.MtmFormPageFormSectionDAObject;
import com.dcivision.form.dao.MtmFormSectionFormElementDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;

/**
  MaintFormSectionFormElementAction.java

  This class is for maint user record.

    @author          Vera Wang
    @company         DCIVision Limited
    @creation date   10/12/2003
    @version         $Revision: 1.43.2.2 $
*/

public class MaintFormSectionFormElementAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.43.2.2 $";

  protected String listName = "";
  public MaintFormSectionFormElementAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.form.dao.FormSectionDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.FORM_SETUP);
  }

  /**
   * setPageTitle
   * set the extend page title and page path.
   * default page path/title will be created by navmode and functionCode
   * @throws ApplicationException 
   */
  public void setPageTitle(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping, ActionForward actionForward) throws ApplicationException{
    MaintFormSectionForm formSectionForm = (MaintFormSectionForm)form;
    FormGroupDAObject groupDAO = new FormGroupDAObject(this.getSessionContainer(request),this.getConnection(request));
    if(!Utility.isEmpty(formSectionForm.getFormGroupID())){
      FormGroup formGroup = (FormGroup)groupDAO.getObjectByID(Integer.valueOf(formSectionForm.getFormGroupID()));
      StringBuffer extendPath = new StringBuffer();
      extendPath.append("<a href=\"ListFormRecord.do?formGroupID="+formSectionForm.getFormGroupID());
      extendPath.append("&opMode="+GlobalConstant.OP_MODE_LIST_RETAIN+"\">");
      extendPath.append(formGroup.getGroupName());
      extendPath.append("</a>");
      request.setAttribute(GlobalConstant.EXTEND_PAGE_PATH, extendPath.toString());
    }
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    AbstractActionForm maintForm = (AbstractActionForm)form;
    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();
    String navMode = (maintForm!=null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();

    FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
    //set status is released.
    if (!Utility.isEmpty(request.getParameter("isRelease")) && "true".equals(request.getParameter("isRelease"))){
      formRecordDAO.releaseFormRecord(request.getParameter("formRecordID"),request.getParameter("formRecordUpdateCount"));
      this.commit(request);
      addMessage(request, MESSAGE_RECORD_UPDATE);   
      maintForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
      request.setAttribute("formRecordStatus",FormRecord.FORM_STATUS_RELEASED);
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
        return forward;
      }
      selectRecord(mapping, maintForm, request, response);
      return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
    }
    
    if (GlobalConstant.OP_MODE_REFRESH.equals(opMode)) {
      // Set the function code for current action.
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
        return forward;
      }
      refreshFormData(mapping, maintForm, request, response);
      //this.selectRecord(mapping,(AbstractActionForm)form,request,response);
      return mapping.findForward(GlobalConstant.NAV_MODE_REFRESH);
    } else if (GlobalConstant.NAV_MODE_PREVIEW.equals(navMode)){
      // Set the function code for current action.
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
        return forward;
      }
      priviewFormData(mapping, maintForm, request, response);
      return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
    } else if (FormRecord.NAV_MODE_OUTLINE.equals(navMode)){
      // Set the function code for current action.
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
        return forward;
      }
      selectRecord(mapping, maintForm, request, response);
      return mapping.findForward(FormRecord.NAV_MODE_OUTLINE);
    } else {
      return super.execute(mapping, form, request, response);
    }
  }

  public void refreshFormData(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {    
  	try {
      SessionContainer sessionCon = this.getSessionContainer(request);
      MaintFormSectionForm formSectionForm = (MaintFormSectionForm)form;
      FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));

      List formPageList = formPageDAO.getDetailListByFormRecordID(new Integer(request.getParameter("formRecordID")));
      Object[][] pageElementArray = null;
      if (!Utility.isEmpty(formPageList)) {
      	pageElementArray = new Object[formPageList.size()][1];
      }
      
      for (int j = 0; j < formPageList.size(); j++){
      	List resultList = new ArrayList();
        FormPage formPage =(FormPage)formPageList.get(j);  
        String formPageID = formPage.getID().toString();
	
	      int listSize = 0;
	      int intNewField =0;
	      int newElementSeq = 0;

	      listSize = TextUtility.parseInteger(request.getParameter("listSize_"+formPageID));
	      intNewField = TextUtility.parseInteger(request.getParameter("newField_"+formPageID));
	      if (!Utility.isEmpty(request.getParameter("newElementSeq_"+formPageID))) {
	        newElementSeq = TextUtility.parseInteger(request.getParameter("newElementSeq_"+formPageID));
	      }      
	      int sum = 0;
	      sum = listSize + intNewField;
	      if (!"null".equals(request.getParameter("formPageTitle_" + formPageID))){
            formPage.setTitle(request.getParameter("formPageTitle_" + formPageID));
          }
  	      formPage.setIsDelete("Y".equals(request.getParameter("delete_" + formPageID)) ? "Y" : "N"); 
	      formPage.setIsDeleteAll("Y".equals(request.getParameter("deleteAll_" + formPageID)) ? "Y" : "N"); 

	      //Get Header Form data
	      FormSection formSection = (FormSection)formSectionForm.getFormData();
	      //Set Header Form data
	      formSectionForm.setFormData(formSection);
	      for (int i = 0; i < TextUtility.parseInteger(request.getParameter("listSize_"+formPageID)); i++){
	        String strElementTypeChooseValue = request.getParameter("formElementType_" + formPageID +"_" + i);
	        if ((strElementTypeChooseValue).equals(FormElementType.ELEMENT_SECTION)) {
	          FormSection tmpFormSection = new FormSection();
	          if (! ("".equals(request.getParameter("formElementID_" + formPageID +"_" + i))) &&
	              ! ("null".equals(request.getParameter("formElementID_" + formPageID +"_" + i))))
	          	
	            tmpFormSection.setID(new Integer(request.getParameter(
	                "formElementID_" + formPageID +"_" + i)));
              tmpFormSection.setIsSelected(true);
	            tmpFormSection.setTitle(new String(request.getParameter(
	                "formElementName_" + formPageID +"_" + i)));
             	tmpFormSection.setSubSection("N");
              
	          String strMandatoryCheckValue = request.getParameter("mandatory_" + formPageID +"_" + i);
	
	          String strDeleteCheckValue = request.getParameter("delete_" + formPageID + '_' + i);
              tmpFormSection.setIsDelete("Delete".equals(request.getParameter("delete_" + formPageID +"_" + i)) ? "Y" : "N"); 
//	          if (strDeleteCheckValue == null || Utility.isEmpty(strDeleteCheckValue) || strDeleteCheckValue != null && !Utility.isEmpty(tmpFormSection.getID())) {
	            resultList.add(tmpFormSection);
//	          }else{
//              listSize--;
//              sum--;
//              newElementSeq--;
//            }
	        } else if (!strElementTypeChooseValue.equals(FormElementType.ELEMENT_SECTION) || !strElementTypeChooseValue.equals(FormElementType.ELEMENT_PAGE)) {
	          FormElement tmpFormElement = new FormElement();
	          if (! ("".equals(request.getParameter("formElementID_" + formPageID +"_" + i))) &&
	              ! ("null".equals(request.getParameter("formElementID_" + formPageID +"_" + i))))
	            tmpFormElement.setID(new Integer(request.getParameter(
	                "formElementID_" + formPageID +"_" + i)));
	          if (! ("".equals(request.getParameter("formElementName_" + formPageID +"_" + i))) &&
	              (!"null".equals(formSection.getID())))
	            tmpFormElement.setFieldName(new String(request.getParameter(
	                "formElementName_" + formPageID +"_" + i)));
              
              if (request.getParameter("selectionOptionNum_" + formPageID + "_" + i) != null
                      && !"".equals(request.getParameter("selectionOptionNum_" + formPageID + "_" + i))
                      && !"null".equals(request.getParameter("selectionOptionNum_" + formPageID + "_" + i))) {
                  tmpFormElement.setOptionNumber(Integer.parseInt(request.getParameter("selectionOptionNum_" + formPageID + "_" + i)));
              }
              
	          String strMandatoryCheckValue = request.getParameter("mandatory_" + formPageID +"_" + i);
	          if (strMandatoryCheckValue == null ) {
	            tmpFormElement.setRequiredFlag("N");
	          }
	          else {
	            tmpFormElement.setRequiredFlag("Y");
	          }
	
	          tmpFormElement.setElementType(strElementTypeChooseValue);          
	          String strDeleteCheckValue = request.getParameter("delete_" + formPageID +"_" + i);
              tmpFormElement.setIsDelete("Delete".equals(request.getParameter("delete_" + formPageID +"_" + i)) ? "Y" : "N");
//	          if (strDeleteCheckValue == null || Utility.isEmpty(strDeleteCheckValue) || strDeleteCheckValue != null && !Utility.isEmpty(tmpFormElement.getID())) {
	            resultList.add(tmpFormElement);            
//	          }else{             
//              listSize--;
//              sum--;
//              newElementSeq--;
//            }
 	        }
	      }
        if (newElementSeq > 0) {
          FormSection tmpFormSection = new FormSection();
          tmpFormSection.setTitle("");
          resultList.add(newElementSeq,tmpFormSection);
          listSize++;
        }
	    	pageElementArray[j][0] = resultList;
	      formSectionForm.setFormElementListData(resultList);
	      formSectionForm.setFormElementList(formSectionForm.getFormElementList());
	      request.setAttribute("formPageID",request.getParameter("formPageID"));
	      request.setAttribute("listSize_"+formPageID, new Integer(listSize));
	      request.setAttribute("newFieldsSize_"+formPageID, new Integer(sum));
	      request.setAttribute("newField_"+formPageID, new Integer(intNewField));
	      request.setAttribute("newElementSeq_"+formPageID,new Integer(newElementSeq));
      }
      
      formSectionForm.setPageElementArray(pageElementArray);
      request.setAttribute("formPageList",formPageList);  
     
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e){
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
    }
  }

  public void refreshList(HttpServletRequest request, String opMode, com.dcivision.framework.bean.AbstractBaseObject obj) {
    java.util.ArrayList list = (java.util.ArrayList)request.getAttribute(this.listName);
    if (list != null) {
      if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
        list.add(obj);
      } else if (GlobalConstant.OP_MODE_UPDATE.equals(opMode)) {
        for (int i = 0; i < list.size(); i++) {
          if (obj.equals(list.get(i))) {
            list.remove(i);
            list.add(i, obj);
          }
        }
      } else if (GlobalConstant.OP_MODE_DELETE.equals(opMode)) {
        for (int i = 0; i < list.size(); i++) {
          if (obj.equals(list.get(i))) {
            list.remove(i);
          }
        }
      }
    }
  }

  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    try {
      Hashtable elementHashtable = new Hashtable();
      MaintFormSectionForm formSectionForm = (MaintFormSectionForm)form;
      String formPageID = null;
      //    get form page
      FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));
      FormSubmissionManager formSubmissionManager = new FormSubmissionManager(this.getSessionContainer(request),this.getConnection(request));

      List formPageList = formPageDAO.getDetailListByFormRecordID(new Integer(request.getParameter("formRecordID")));
       for (int j = 0; j < formPageList.size(); j++){
      	FormPage formPage =(FormPage)formPageList.get(j);
      	formPageID = formPage.getID().toString();
 	      //get form section
	      Integer FormSectionID = TextUtility.parseIntegerObj(formSectionForm.getID());
	      FormSectionDAObject formSectionDAO = new FormSectionDAObject(this.getSessionContainer(request), this.getConnection(request));
	      List formSectionList = formSectionDAO.getListByFormPageID(formPage.getID());
	      //get form element
	      int elementSize = 0;
	      for (int i = 0; i < formSectionList.size(); i++) {
	
	        FormSection formSection = (FormSection)formSectionList.get(i);
	
	        FormElementDAObject FormElementDAO = new FormElementDAObject(this.getSessionContainer(request), this.getConnection(request));
	        List formElementList = FormElementDAO.getListByFormSectionID(
	            formSection.getID());
	        elementHashtable.put(formSection.getID(),formElementList);
	        elementSize  = elementSize + formElementList.size() ;
	      }
	      request.setAttribute("formSectionList"+j,formSectionList);
	      request.setAttribute("formElementHashtable"+j,elementHashtable);
	      request.setAttribute("formPageID",formPageID);
	      request.setAttribute("listSize_"+formPageID,new Integer(formSectionList.size()+elementSize));
      }    
      request.setAttribute("formPageList",formPageList);
      String sHasElement = formSubmissionManager.hasElement(request.getParameter("formRecordID")) ? "true" : "false";
      request.setAttribute("sHasElement",sHasElement);
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
    } finally {}
  }

/*  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintFormSectionForm formSectionForm = (MaintFormSectionForm)form;
    try {
      // released the Form Record.
      if (FormRecord.FORM_STATUS_RELEASED.equals(formSectionForm.getStatus())) {
        String formRecordID = request.getParameter("formRecordID");
        String updateCount = request.getParameter("formRecordUpdateCount");
        FormRecordDAObject formRecordDAO = new FormRecordDAObject(
            this.getSessionContainer(request),this.getConnection(request));
        formRecordDAO.releaseFormRecord(formRecordID,updateCount);
      }
     // refreshList(request, GlobalConstant.OP_MODE_INSERT, formSection);
     this.selectRecord(mapping,(AbstractActionForm)form,request,response);

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {}

  }*/

  public void insertRecord(ActionMapping mapping,
                           AbstractActionForm form,
                           HttpServletRequest request,
                           HttpServletResponse response) throws ApplicationException {
    
  	// if Satus is RELEASED.
    try {

      if (FormRecord.FORM_STATUS_RELEASED.equals(request.getParameter("status"))) {
        String formRecordID = request.getParameter("formRecordID");
        String updateCount = request.getParameter("formRecordUpdateCount");
        FormRecordDAObject formRecordDAO = new FormRecordDAObject(
            this.getSessionContainer(request), this.getConnection(request));
        formRecordDAO.releaseFormRecord(formRecordID, updateCount);
        request.setAttribute("formRecordStatus",FormRecord.FORM_STATUS_RELEASED);
      }
    }
    catch (Exception e) {
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }
    // Create Form Section
    int listSize = 0;
    int intNewField = 0;
    int newElementSeq = 0;
    listSize = TextUtility.parseInteger(request.getParameter("lastlistSizeTotal"));
    intNewField = TextUtility.parseInteger(request.getParameter("newField"));
    if (!Utility.isEmpty(request.getParameter("newElementSeq"))) {
      newElementSeq = TextUtility.parseInteger(request.getParameter(
          "newElementSeq"));
    }


    //int sum = 0;
    //sum = listSize + intNewField;
    
    int pageSeqNo = 0;
    int sectionSeqNo = 0;
    int elementSeqNo = 0;
    String formPageID = null;
    String lastPageID = null;
    String sectionID = null;
    String objectName = null;
    String objectID = null;
    String lastSectionID = null;
    String strDeleteCheckValue = null;
    //String strDeletePageValue = null;    

    FormPageDAObject formPageDAO = new FormPageDAObject(this.
            getSessionContainer(request), this.getConnection(request));
    FormSectionDAObject formSectionDAO = new FormSectionDAObject(this.
            getSessionContainer(request), this.getConnection(request));
    FormElementDAObject formElementDAO = new FormElementDAObject(this.
            getSessionContainer(request), this.getConnection(request));
    MtmFormSectionFormElementDAObject mtmFormSectionFormElementDAO =
        new MtmFormSectionFormElementDAObject(
        this.getSessionContainer(request), this.getConnection(request));
    MtmFormPageFormSectionDAObject mtmFormPageFormSectionDAO = new
        MtmFormPageFormSectionDAObject(this.getSessionContainer(request),
                                       this.getConnection(request));
  	// list all page
    int pageListSize = new Integer(request.getParameter("pageListSize")).intValue();
    for (int nn = 1; nn <= pageListSize; nn++){    
    		String pageID = request.getParameter("formPageID_"+nn);
    		if(nn==1){
    		  formPageID = pageID;
              lastPageID = formPageID;
    		  pageSeqNo = 0;
    		}
    			
    		
    		
    		int elementNo = new Integer(request.getParameter("listSize_"+pageID)).intValue();
    		//begin delete the page
    		if (!Utility.isEmpty(request.getParameter("delete_"+pageID)) || !Utility.isEmpty(request.getParameter("deleteAll_"+pageID))){
     			if(nn==1){
     				formPageID = request.getParameter("formPageID_"+(nn+1));
     			}
    			formPageDAO.deleteObjectByID(new Integer(pageID));  			
    		}else{
    			lastPageID = pageID;
    			FormPage templateFormPage =(FormPage) formPageDAO.getObjectByID(new Integer(pageID));
    			templateFormPage.setPageNo(new Integer(pageSeqNo));
                templateFormPage.setTitle(request.getParameter("formPageTitle_"+pageID));
    			formPageDAO.updateObject(templateFormPage);
    			pageSeqNo++;
    		}
        
        for (int i = 0; i < elementNo; i++){
          String strmandatory = null;
          String subSection = null;
          objectID = request.getParameter("formElementID_" + pageID + '_' + i);
          objectName = request.getParameter("formElementName_" + pageID + '_' + i);
          strDeleteCheckValue = request.getParameter("delete_" + pageID + '_' + i);
          if ((!Utility.isEmpty(request.getParameter("mandatory_" + pageID + '_' +i))))
          	strmandatory = "Y";
          else
          	strmandatory = "N";
          if ((!Utility.isEmpty(request.getParameter("subSection_" + pageID + '_' +i))))
            subSection = "Y";
          else
            subSection = "N";      
          if((request.getParameter("formElementType_" + pageID + '_' + i)).equals(FormElementType.ELEMENT_PAGE)){
          	//Handle Page
          	FormPage tmpFormPage = new FormPage();
          	tmpFormPage.setFormRecordID(new Integer(request.getParameter("formRecordID")));
          	tmpFormPage.setTitle(objectName);
          	FormPage formPage = null;
          	if(!Utility.isEmpty(strDeleteCheckValue) && !Utility.isEmpty(objectID) && !"null".equals(objectID)){
          		if(!Utility.isEmpty(formPageDAO.getObjectByID(new Integer(objectID)))){
                //Delete page
          			formPageDAO.deleteObjectByID(new Integer(objectID));
          		}
          	}
          	if ( (Utility.isEmpty(strDeleteCheckValue)) &&
                !Utility.isEmpty(tmpFormPage.getTitle()) ) {
//	              pageSeqNo++;
	          	if (Utility.isEmpty(objectID) || "null".equals(objectID)) {
	              //Insert A New Page
	          		tmpFormPage.setPageNo(new Integer(pageSeqNo));
	              formPage = (FormPage) formPageDAO.insertObject( tmpFormPage);
	              lastPageID = formPage.getID().toString();
	              pageSeqNo++;
	            } else { //update Page
	            	formPageID = objectID;
	              lastPageID = formPageID;
	              //Update Form_Section
	              tmpFormPage.setPageNo(new Integer(pageSeqNo));
	              tmpFormPage = (FormPage) formPageDAO.getObjectByID(new Integer(formPageID));
	              tmpFormPage.setTitle(objectName);
	              formPageDAO.updateObject(tmpFormPage);
	              pageSeqNo++;
	              }//-----------------------------         	  
          	}
          }
    	    else if ((request.getParameter("formElementType_" + pageID + '_' + i)).equals(FormElementType.ELEMENT_SECTION)) {
        		//Handle section
            FormSection tmpFormSection = new FormSection();
            MtmFormPageFormSection tmpMtmFormPageFormSection = new
                MtmFormPageFormSection();
            tmpFormSection.setTitle(objectName);
            tmpFormSection.setSubSection(subSection);

            if (!Utility.isEmpty(strDeleteCheckValue) && !Utility.isEmpty(objectID) && !"null".equals(objectID)) {
              if (!Utility.isEmpty(formSectionDAO.getObjectByID(new Integer(
                    objectID)))) {
                //Delete Section               
                this.deleteSectionRecord(pageID,objectID,request,response);
                //formSectionDAO.deleteObjectByID(new Integer(objectID));                 
              }
            }

            if ( (Utility.isEmpty(strDeleteCheckValue)) &&
                !Utility.isEmpty(tmpFormSection.getTitle()) ) {
              sectionSeqNo++;
              
              tmpMtmFormPageFormSection.setPageID(new Integer(lastPageID));              
              FormSection formSection = null;
              
              if (Utility.isEmpty(objectID) || "null".equals(objectID)) {
                //Insert A New Section
                formSection = (FormSection) formSectionDAO.insertObject( tmpFormSection);
                lastSectionID = formSection.getID().toString();
                //Insert Mtm_Form_Page_Form_Section
                tmpMtmFormPageFormSection.setSectionID(formSection.getID());
                tmpMtmFormPageFormSection.setSectionSeq(new Integer(sectionSeqNo));
                mtmFormPageFormSectionDAO.insertObject(tmpMtmFormPageFormSection);
              } else { //update section
                sectionID = objectID;
                lastSectionID = sectionID;
                //Update Form_Section
                tmpFormSection = (FormSection) formSectionDAO.getObjectByID(new Integer(sectionID));
                tmpFormSection.setTitle(objectName);
                tmpFormSection.setSubSection(subSection);
                formSectionDAO.updateObject(tmpFormSection);

                //Update Mtm_Form_Page_Form_Section
                try {
                  tmpMtmFormPageFormSection = (MtmFormPageFormSection)
                    mtmFormPageFormSectionDAO.
                    getObjectBySectionID(new Integer(sectionID));
                  tmpMtmFormPageFormSection.setPageID(new Integer(lastPageID));
                  tmpMtmFormPageFormSection.setSectionSeq(new Integer(sectionSeqNo));
                  mtmFormPageFormSectionDAO.updateObject(tmpMtmFormPageFormSection);
                } catch (ApplicationException appEx) {
                  //if not found it in mtm then insert it.
                  if (ErrorConstant.DB_RECORD_NOT_FOUND_ERROR.equals(appEx.getMsgCode())) {
                    tmpMtmFormPageFormSection = new MtmFormPageFormSection();
                    tmpMtmFormPageFormSection.setPageID(new Integer(lastPageID));
                    tmpMtmFormPageFormSection.setSectionID(new Integer(sectionID));
                    tmpMtmFormPageFormSection.setSectionSeq(new Integer(sectionSeqNo));
                    mtmFormPageFormSectionDAO.insertObject(tmpMtmFormPageFormSection);
                  }
                }    
             }
           } 
          }else {
            //Handle element
            if (!Utility.isEmpty(strDeleteCheckValue) && !Utility.isEmpty(objectID) && !"null".equals(objectID)) {
              if (!Utility.isEmpty(formElementDAO.getObjectByID(new Integer(
                  objectID)))) {
                //Delete Element
                this.deleteElementRecord(objectID,request,response);
                //formElementDAO.deleteObjectByID(new Integer(objectID));
              }
            }

            if ( (Utility.isEmpty(strDeleteCheckValue)) ) {
              elementSeqNo++;
              String elementID = objectID;
              FormElement formElement = null;
              if (Utility.isEmpty(elementID) || "null".equals(elementID)) {
                //Insert a new Element
                FormElement tmpFormElement = new FormElement();
                tmpFormElement.setFieldName(objectName);
                tmpFormElement.setElementType(request.getParameter(
                    "formElementType_" + pageID + '_' + i));
                tmpFormElement.setRequiredFlag(strmandatory);
                tmpFormElement.setIsLabel("N");
                formElement = (FormElement) formElementDAO.insertObject(
                    tmpFormElement);
                //Insert Mtm_Form_Section_Form_Element Table
                MtmFormSectionFormElement tmpFormSectionFormElement = new
                    MtmFormSectionFormElement();

                tmpFormSectionFormElement.setElementID(formElement.getID());
                tmpFormSectionFormElement.setSectionID(new Integer(lastSectionID));
                tmpFormSectionFormElement.setElementSeq(new Integer(elementSeqNo));
                mtmFormSectionFormElementDAO.insertObject(tmpFormSectionFormElement);

              } else {
                //Update this Element
                FormElement tmpFormElement = (FormElement) formElementDAO.
                    getObjectByID(new Integer(elementID));
                tmpFormElement.setFieldName(objectName);
                tmpFormElement.setElementType(request.getParameter(
                    "formElementType_" + pageID + '_' + i));
                tmpFormElement.setRequiredFlag(strmandatory);
                tmpFormElement.setIsLabel("N");
                formElementDAO.updateObject(tmpFormElement);

                //Update Mtm_Form_Section_Form_Element Table
                try {
                  if(Utility.isEmpty(sectionID) || "null".equals(sectionID)){
                    //Insert Mtm_Form_Section_Form_Element Table
                    MtmFormSectionFormElement tmpFormSectionFormElement = new
                        MtmFormSectionFormElement();
                    tmpFormSectionFormElement.setElementID(new Integer(elementID));
                    tmpFormSectionFormElement.setSectionID(new Integer(
                        lastSectionID));
                    tmpFormSectionFormElement.setElementSeq(new Integer(
                        elementSeqNo));
                    mtmFormSectionFormElementDAO.insertObject(tmpFormSectionFormElement);
                  }else{//Update Mtm_Form_Section_Form_Element Table
                    MtmFormSectionFormElement tmpFormSectionFormElement = (
                        MtmFormSectionFormElement)
                        mtmFormSectionFormElementDAO.getObjectByElementID(
                        new Integer(elementID));
                    tmpFormSectionFormElement.setSectionID(new Integer(
                        lastSectionID));
                    tmpFormSectionFormElement.setElementSeq(new Integer(
                        elementSeqNo));
                    mtmFormSectionFormElementDAO.updateObject(tmpFormSectionFormElement);
                  }
                } catch (ApplicationException appEx) {
                  //if not found it in mtm then insert it.
                  if (ErrorConstant.DB_RECORD_NOT_FOUND_ERROR.equals(appEx.getMsgCode())) {
                    MtmFormSectionFormElement tmpFormSectionFormElement = new
                        MtmFormSectionFormElement();

                    tmpFormSectionFormElement.setElementID(new Integer(elementID));
                    tmpFormSectionFormElement.setSectionID(new Integer(lastSectionID));
                    tmpFormSectionFormElement.setElementSeq(new Integer(elementSeqNo));
                    mtmFormSectionFormElementDAO.insertObject(tmpFormSectionFormElement);
                  }
                }
              }
            }
          }
        }    	
    }


    lastPageID = request.getParameter("formPageID");

   // request.setAttribute("listSize", new Integer(listSize));
    this.selectRecord(mapping,form,request,response);
  }
  
  public void deleteSectionRecord(String pageID, String delSectionID,
			HttpServletRequest request, HttpServletResponse response)
			throws ApplicationException {
		Integer preSectionID = new Integer(-1);

		int delSectionSeq = 0;
		int preSectionSeq = 0;
		MtmFormPageFormSection mtmFormPageFormSection = new MtmFormPageFormSection();
		MtmFormPageFormSectionDAObject mtmFormPageFormSectionDAO = new MtmFormPageFormSectionDAObject(
				this.getSessionContainer(request), this.getConnection(request));
		MtmFormSectionFormElementDAObject mtmFormSectionFormElementDAO = new MtmFormSectionFormElementDAObject(
				this.getSessionContainer(request), this.getConnection(request));
		FormSectionDAObject formSectionDAO = new FormSectionDAObject(this
				.getSessionContainer(request), this.getConnection(request));

		try{
			// Get the seqNo of deleted section
			mtmFormPageFormSection = (MtmFormPageFormSection) mtmFormPageFormSectionDAO
			.getObjectBySectionID(new Integer(delSectionID));
			if (!Utility.isEmpty(mtmFormPageFormSection)){
				delSectionSeq = (mtmFormPageFormSection.getSectionSeq()).intValue();
			}
			if (delSectionSeq != 0) {
				// Get all sections of page [formPageID]
				List mtmFormPageFormSectionList = mtmFormPageFormSectionDAO
				.getListByPageID(new Integer(pageID));
				// Get the previous section at the deleted section
				for (int i = mtmFormPageFormSectionList.size() - 1; i >= 0; i--) {
					if (i < 0) {
						break;
					}
					MtmFormPageFormSection tmpMtmFormPageFormSection = (MtmFormPageFormSection) mtmFormPageFormSectionList
					.get(i);
					if (tmpMtmFormPageFormSection.getSectionSeq().intValue() < delSectionSeq) {
						preSectionID = tmpMtmFormPageFormSection.getSectionID();
						preSectionSeq = tmpMtmFormPageFormSection.getSectionSeq()
						.intValue();
						
						// Get last element seqNO of pre section.
						List mtmFormSectionFormElementList = mtmFormSectionFormElementDAO
						.getListBySectionID(preSectionID);
						MtmFormSectionFormElement lastMtmFormSection = (MtmFormSectionFormElement) (mtmFormSectionFormElementList
								.get(mtmFormSectionFormElementList.size() - 1));
						Integer lastElementSeq = lastMtmFormSection.getElementSeq();
						// Update all Elements's seqNo of pre section
						List delElementList = mtmFormSectionFormElementDAO
						.getListBySectionID(new Integer(delSectionID));
						for (int j = 0; j < delElementList.size(); j++) {
							MtmFormSectionFormElement tmpUpdateMtmSectionElement = (MtmFormSectionFormElement) delElementList
							.get(j);
							tmpUpdateMtmSectionElement.setElementSeq(new Integer(
									lastElementSeq.intValue() + j + 1));
							tmpUpdateMtmSectionElement.setSectionID(preSectionID);
							mtmFormSectionFormElementDAO
							.updateObject(tmpUpdateMtmSectionElement);
						}
					}
				}
				// Delete section in MTM_FORM_PAGE_FORM_SECTION table
				mtmFormPageFormSectionDAO.deleteObject(mtmFormPageFormSection);
				
				// Delete section in FORM_SECTION table
				formSectionDAO.deleteObjectByID(new Integer(delSectionID));
				
			}
		}catch (ApplicationException appEx) {
			if (!appEx.getMsgCode().equals(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR)){
				throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
			}
		}
	}
  
  public void deleteElementRecord(String delElementID,
			HttpServletRequest request, HttpServletResponse response)
			throws ApplicationException {
		int delElementSeq = 0;
		MtmFormSectionFormElement mtmFormSectionFormElement = new MtmFormSectionFormElement();
		MtmFormSectionFormElementDAObject mtmFormSectionFormElementDAO = new MtmFormSectionFormElementDAObject(
				this.getSessionContainer(request), this.getConnection(request));
		FormElementDAObject formElementDAO = new FormElementDAObject(this
				.getSessionContainer(request), this.getConnection(request));
		try{
			// Get the seqNo of deleted Element
			mtmFormSectionFormElement = (MtmFormSectionFormElement) mtmFormSectionFormElementDAO
			.getObjectByElementID(new Integer(delElementID));
			if (!Utility.isEmpty(mtmFormSectionFormElement)){
				delElementSeq = (mtmFormSectionFormElement.getElementSeq()).intValue();
			}
			if (delElementSeq != 0) {
				// Delete section in MTM_FORM_PAGE_FORM_SECTION table
				mtmFormSectionFormElementDAO
				.deleteObject(mtmFormSectionFormElement);
				
				// Delete section in FORM_SECTION table
				formElementDAO.deleteObjectByID(new Integer(delElementID));
				
			}
		}catch (ApplicationException appEx) {
			if (!appEx.getMsgCode().equals(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR)){
				throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
			}
		}
  }
  
  public void priviewFormData(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {    
  	try {
  		SessionContainer sessionCon = this.getSessionContainer(request);
  		MaintFormSectionForm formSectionForm = (MaintFormSectionForm)form;
  		FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));
  		FormSectionDAObject formSectionDAO = new FormSectionDAObject(this.getSessionContainer(request), this.getConnection(request));
  		FormElementDAObject formElementDAO = new FormElementDAObject(this.getSessionContainer(request), this.getConnection(request));
  		
  		List formPageList = formPageDAO.getDetailListByFormRecordID(new Integer(request.getParameter("formRecordID")));
  		int pageSize = formPageList.size();
  		String lastPageID = "", dummyPageID = "";
  		int newPageSeq = 0, newPageInElementSeq = 0;
  		Random random = new Random();
  		
  		for (int p = 0; p < formPageList.size(); p++){
  			FormPage tmpFormPage =(FormPage)formPageList.get(p);  
  			String tmpPageID = tmpFormPage.getID().toString();
  			for (int i = 0; i < TextUtility.parseInteger(request.getParameter("listSize_"+tmpPageID)); i++){
  				String strDeleteCheckValue = request.getParameter("delete_" + tmpPageID +"_" + i);
  				if (request.getParameter("formElementType_" + tmpPageID +"_" + i).equals(FormElementType.ELEMENT_PAGE)
  						&& (Utility.isEmpty(strDeleteCheckValue) || "null".equals(strDeleteCheckValue)) ){               
  					pageSize++;
  				}
  			}
  		}
  		Object[][] pageElementArray = null;
  		if (!Utility.isEmpty(formPageList)) {
  			pageElementArray = new Object[pageSize][1];
  		}
  		
  		for (int j = 0; j < pageSize; j++){
  			List resultList = new ArrayList();
  			String formPageID = "";
  			FormPage formPage = null;
  			int listSize = 0;
  			int intNewField =0;
  			int newElementSeq = 0;
  			
  			if (!Utility.isEmpty(formPageList.get(j)) && !"null".equals(formPageList.get(j)) &&  !"dummyPageID".equals(dummyPageID)){
  				formPage =(FormPage)formPageList.get(j);  
  				formPageID = formPage.getID().toString();
  				lastPageID = formPageID;
  				dummyPageID = formPageID;
  				newPageInElementSeq = 0;
  				newPageSeq = 0;
  				if (!"null".equals(request.getParameter("formPageTitle_" + formPageID))){
  					formPage.setTitle(request.getParameter("formPageTitle_" + formPageID));
  				}
  			}else{
  				formPageID = lastPageID;     
  				formPage =(FormPage)formPageList.get(j); 
  			}
  			
  			listSize = TextUtility.parseInteger(request.getParameter("listSize_"+formPageID));        
  			int sum = 0;
  			sum = listSize + intNewField;
  			
  			//Get Header Form data
  			FormSection formSection = (FormSection)formSectionForm.getFormData();
  			//Set Header Form data
  			formSectionForm.setFormData(formSection);
  			int startElement = 0; 
  			if (newPageInElementSeq>0){
  				startElement = newPageInElementSeq +1; // new page 
  			}
  			for (int i = startElement; i < TextUtility.parseInteger(request.getParameter("listSize_"+formPageID)); i++){
  				String strElementTypeChooseValue = request.getParameter("formElementType_" + formPageID +"_" + i);
  				if (strElementTypeChooseValue.equals(FormElementType.ELEMENT_PAGE)){
  					FormPage tmpFormPage = new FormPage();           
  					String strDeleteCheckValue = request.getParameter("delete_" + formPageID +"_" + i);
  					if (strDeleteCheckValue == null || Utility.isEmpty(strDeleteCheckValue) || strDeleteCheckValue != null && !Utility.isEmpty(tmpFormPage.getID())) {
  						tmpFormPage.setTitle(new String(request.getParameter(
  								"formElementName_" + formPageID +"_" + i))) ; 
  						dummyPageID = "dummyPageID";     
  						formPageID = lastPageID;             
  						int number = random.nextInt(100);
  						tmpFormPage.setID(new Integer(number*99999));
  						if (! ("".equals(request.getParameter("formElementName_" + formPageID +"_" + i))))
  							tmpFormPage.setTitle(new String(request.getParameter(
  									"formElementName_" + formPageID +"_" + i)));
  						formPageList.add(j+1,tmpFormPage);
  						newPageInElementSeq = i;
  						newPageSeq++;
  						break;
  					}  					
  				}else if ((strElementTypeChooseValue).equals(FormElementType.ELEMENT_SECTION)) {					
  					FormSection tmpFormSection = new FormSection();
  					String strMandatoryCheckValue = request.getParameter("mandatory_" + formPageID +"_" + i); 					
  					String strDeleteCheckValue = request.getParameter("delete_" + formPageID + '_' + i);
  					
  					if (strDeleteCheckValue == null || Utility.isEmpty(strDeleteCheckValue) || strDeleteCheckValue != null && !Utility.isEmpty(tmpFormSection.getID())) {
  						if (! ("".equals(request.getParameter("formElementID_" + formPageID +"_" + i))) &&
  								! ("null".equals(request.getParameter("formElementID_" + formPageID +"_" + i)))){
  							tmpFormSection = (FormSection)formSectionDAO.getObjectByID(new Integer(request.getParameter("formElementID_" + formPageID +"_" + i)));                
  						}                
  						tmpFormSection.setIsSelected(true);
  						tmpFormSection.setTitle(!"null".equals(request.getParameter("formElementName_" + formPageID +"_" + i)) ? request.getParameter("formElementName_" + formPageID +"_" + i) : "");
  						tmpFormSection.setSubSection("N");
  						tmpFormSection.setIsDelete("Delete".equals(request.getParameter("delete_" + formPageID +"_" + i)) ? "Y" : "N");
  						resultList.add(tmpFormSection);
  					}else{
  						listSize--;
  						sum--;
  						newElementSeq--;
  					}
  					
  					dummyPageID = "";  
  				} else if (!strElementTypeChooseValue.equals(FormElementType.ELEMENT_SECTION) || !strElementTypeChooseValue.equals(FormElementType.ELEMENT_PAGE)) {
  					FormElement tmpFormElement = new FormElement();
  					String strDeleteCheckValue = request.getParameter("delete_" + formPageID +"_" + i);
  					if (strDeleteCheckValue == null || Utility.isEmpty(strDeleteCheckValue) || strDeleteCheckValue != null && !Utility.isEmpty(tmpFormElement.getID())) {
  						if (! ("".equals(request.getParameter("formElementID_" + formPageID +"_" + i))) &&
  								! ("null".equals(request.getParameter("formElementID_" + formPageID +"_" + i)))){
  							tmpFormElement = (FormElement)formElementDAO.getObjectByID(new Integer(request.getParameter("formElementID_" + formPageID +"_" + i)));
  						}
  						tmpFormElement.setFieldName(!"null".equals(request.getParameter("formElementName_" + formPageID +"_" + i)) ? request.getParameter("formElementName_" + formPageID +"_" + i) : "");          
  						String strMandatoryCheckValue = request.getParameter("mandatory_" + formPageID +"_" + i);
  						if (strMandatoryCheckValue == null ) {
  							tmpFormElement.setRequiredFlag("N");
  						}else {
  							tmpFormElement.setRequiredFlag("Y");
  						}           
  						tmpFormElement.setElementType(strElementTypeChooseValue);          
  						tmpFormElement.setIsDelete("Delete".equals(request.getParameter("delete_" + formPageID +"_" + i)) ? "Y" : "N");
  						
  						resultList.add(tmpFormElement);            
  					}else{             
  						listSize--;
  						sum--;
  						newElementSeq--;
  					}
  					dummyPageID = "";  
  				}
  			}
  			if (newElementSeq > 0) {
  				FormSection tmpFormSection = new FormSection();
  				tmpFormSection.setTitle("");
  				resultList.add(newElementSeq,tmpFormSection);
  				listSize++;
  			}
  			pageElementArray[j][0] = resultList;
  			formSectionForm.setFormElementListData(resultList);
  			formSectionForm.setFormElementList(formSectionForm.getFormElementList());
  			request.setAttribute("SHOW_HEADER_FOOTER", "N");
  		}
  		
  		formSectionForm.setPageElementArray(pageElementArray);
  		request.setAttribute("formPageList",formPageList);    
  		request.setAttribute("formPageListName",formPageList);  // for page Tab  
  	} catch (ApplicationException appEx) {
  		throw appEx;
  	} catch (Exception e){
  		log.error(e, e);
  		throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
  	} finally {
  	}
  }
}
